<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>btn-1</button>
    <button>btn-2</button>
    <button>btn-3</button>
    <button>btn-4</button>
    <button>btn-5</button>
    <script>
        /**
         * 给每个按钮绑定事件，打印当前按钮的索引
         */

        //TODO step1: 获取按钮
        var btns = document.querySelectorAll('button');
        //TODO step2: 绑定事件
        for (var i = 0; i < btns.length; i++) {

            (index => {
                var btn = btns[index];
                btn.onclick = () => {
                    console.log(index)
                }
            })(i);// 匿名函数传参，i -> index
            // ES5闭包解决办法，ES6用let解决
        }
    </script>
</body>

</html>